<template>
  <div class="display-card">
    <div v-if="fileGroups.length > 0" class="card-container">
      <div v-bind="containerProps" class="virtual-container">
        <div v-bind="wrapperProps">
          <div v-for="group in list" :key="group.data.date">
            <DateGroup :date="group.data.date">
              <div class="card-grid">
                <FileCard
                  v-for="file in group.data.files"
                  :key="file.id"
                  :file="file"
                  @card-click="onCardClick"
                  @download="onDownload"
                  @delete="onDelete"
                  @preview-image="onPreviewImage"
                />
              </div>
            </DateGroup>
          </div>
        </div>
      </div>
    </div>
    <EmptyState v-else />

    <!-- 图片预览组件 -->
    <ImagePreview
      ref="imagePreviewRef"
      :images="previewImages"
      :visible="showPreview"
      :start-index="currentPreviewIndex"
      @hide="showPreview = false"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { useVirtualList } from '@vueuse/core'
import DateGroup from './DateGroup.vue'
import FileCard from './FileCard.vue'
import EmptyState from './EmptyState.vue'
import ImagePreview from '@/libs/ImagePreview/index.vue'

const props = defineProps({
  files: {
    type: Array,
    required: true
  }
})

const emit = defineEmits(['card-click', 'download', 'delete'])

// 图片预览相关
const imagePreviewRef = ref(null)
const showPreview = ref(false)
const currentPreviewIndex = ref(0)
const currentPreviewFile = ref(null)

// 提取所有图片文件用于预览
const previewImages = computed(() => {
  if (!props.files) return []

  return props.files
    .filter((file: any) => file.type === 'image' && file.previewUrl)
    .map((file: any) => ({
      src: file.previewUrl,
      title: file.name,
      alt: file.name
    }))
})

// 按日期分组文件
const fileGroups = computed(() => {
  const groups = {}

  if (props.files) {
    props.files.forEach((file) => {
      // 使用日期作为分组键（年-月-日）
      const dateKey = new Date(file.date).toISOString().split('T')[0]
      if (!groups[dateKey]) {
        groups[dateKey] = {
          date: dateKey,
          files: []
        }
      }
      groups[dateKey].files.push(file)
    })

    // 按日期排序（最新的在前）
    const sortedGroups = Object.values(groups).sort(
      (a: any, b: any) => new Date(b.date).getTime() - new Date(a.date).getTime()
    )

    return sortedGroups
  }

  return []
})

// 使用虚拟列表
const { list, containerProps, wrapperProps } = useVirtualList(fileGroups, {
  itemHeight: (idx) => {
    const group = fileGroups.value[idx]
    if (!group) return 0

    // 日期头部高度
    const headerHeight = 40
    // 单个卡片高度
    const cardHeight = 220
    // 每行卡片数量 (根据屏幕宽度估算)
    const cardsPerRow = Math.floor((window.innerWidth - 48) / 250) || 1
    // 行数
    const rowsCount = Math.ceil(group.files.length / cardsPerRow)
    // 行间距
    const rowGap = 16

    return headerHeight + rowsCount * cardHeight + (rowsCount - 1) * rowGap
  },
  overscan: 5 // 预渲染的额外项目数量
})

// 处理图片预览
const onPreviewImage = (file: any) => {
  if (file.type !== 'image' || !file.previewUrl) return

  currentPreviewFile.value = file

  // 查找当前图片在预览列表中的索引
  const index = previewImages.value.findIndex((img: any) => img.src === file.previewUrl)

  if (index !== -1) {
    currentPreviewIndex.value = index
    showPreview.value = true
  }
}

// 事件处理
const onCardClick = (file: any): void => {
  emit('card-click', file)
}

const onDownload = (file: any): void => {
  emit('download', file)
}

const onDelete = (file: any): void => {
  emit('delete', file)
}
</script>

<style scoped>
.display-card {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0; /* 重要：允许内容收缩 */
}

.card-container {
  width: 100%;
  height: 100%;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.virtual-container {
  flex: 1;
  min-height: 0; /* 重要：允许内容收缩 */
  overflow-y: auto;
}

.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .card-grid {
    grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
    gap: 12px;
  }
}

@media (max-width: 480px) {
  .card-grid {
    grid-template-columns: 1fr;
    gap: 8px;
  }
}
</style>
